<template>
  <div>
    <div class="container" :style='{
      "minHeight": "100vh",
      "backgroundAttachment": "fixed",
      "alignItems": "center",
      "background": "url(/assets/img/bg.jpg)",
      "display": "flex",
      "width": "100%",
      "backgroundSize": "cover",
      "backgroundPosition": "center center",
      "backgroundRepeat": "no-repeat",
      "justifyContent": "center"
    }'>
      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        :style='{
          "padding": "40px 20px 80px",
          "boxShadow": "0px 4px 10px 0px #78ABC3",
          "margin": "0",
          "outline": "4px solid #78ABC3",
          "borderRadius": "0",
          "outlineOffset": "30px",
          "background": "#fff",
          "width": "500px",
          "height": "auto"
        }'
      >
        <div :style='{
          "margin": "0 0 10px 0",
          "color": "#000",
          "textAlign": "center",
          "width": "100%",
          "lineHeight": "60px",
          "fontSize": "26px",
          "textShadow": "4px 4px 2px rgba(120, 171, 195, 0.3)",
          "fontWeight": "bold"
        }' class="title-container">{{ title }}</div>

        <!-- 基本信息 -->
        <div class="form-group" :style='{"padding":"10px","margin":"0 auto 20px","borderRadius":"8px","background":"#fff","width":"80%","borderWidth":"0 0 0px 0","height":"auto"}'>
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="请输入姓名"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
        </div>
        
        <!-- 学生特有字段 -->
        <div class="form-group" v-if="loginTable === 'xuesheng'" :style='{"padding":"10px","margin":"0 auto 20px","borderRadius":"8px","background":"#fff","width":"80%","borderWidth":"0 0 0px 0","height":"auto"}'>
          <el-form-item prop="xingbie1">
            <el-input
              v-model="registerForm.xingbie1"
              placeholder="请输入性别"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>


          <el-form-item prop="nianling1">
            <el-input
              v-model="registerForm.nianling1"
              placeholder="请输入年龄"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>

          

          <el-form-item prop="loudong1">
            <el-input
              v-model="registerForm.loudong1"
              placeholder="请输入楼栋号"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>

          
          <el-form-item prop="sushe1">
            <el-input
              v-model="registerForm.sushe1"
              placeholder="请输入宿舍"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="yuanxi1">
            <el-input
              v-model="registerForm.yuanxi1"
              placeholder="请输入院系"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
        </div>
        
        <!-- 宿管特有字段 -->
        <div class="form-group" v-if="loginTable === 'suguan'" :style='{"padding":"10px","margin":"0 auto 20px","borderRadius":"8px","background":"#fff","width":"80%","borderWidth":"0 0 0px 0","height":"auto"}'>
          <el-form-item prop="xingbie2">
            <el-input
              v-model="registerForm.xingbie2"
              placeholder="请输入性别"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="loudong2">
            <el-input
              v-model="registerForm.loudong2"
              placeholder="请输入负责楼栋号"
              :style='{
                "border": "1px solid #ddd",
                "padding": "0 10px",
                "boxShadow": "0px 0px 0px #78ABC3",
                "outline": "none",
                "color": "#333",
                "width": "100%",
                "fontSize": "14px",
                "height": "44px"
              }'
            ></el-input>
          </el-form-item>

        </div>
        
        <div :style='{"margin":"20px auto","alignItems":"center","display":"flex","width":"80%"}'>
          <el-button :style='{
            "border": "0",
            "cursor": "pointer",
            "padding": "0 0",
            "margin": "0 20px 0 0",
            "outline": "none",
            "color": "#fff",
            "borderRadius": "4px",
            "background": "#78ABC3",
            "width": "128px",
            "lineHeight": "44px",
            "fontSize": "14px",
            "height": "44px"
          }' type="primary" @click="submitForm(formRef)">注册</el-button>
          
          <el-button :style='{
            "border": "0",
            "cursor": "pointer",
            "padding": "0 0",
            "margin": "0",
            "outline": "none",
            "color": "#fff",
            "borderRadius": "4px",
            "background": "#909399",
            "width": "128px",
            "lineHeight": "44px",
            "fontSize": "14px",
            "height": "44px"
          }' @click="goBack">返回登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/utils/api'

const router = useRouter()
const formRef = ref(null)

const loginTable = localStorage.getItem('loginTable') || ''

// 表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  phone: '',
  // 学生特有字段
  xingbie1: '',
  nianling1: '',
  sushe1: '',
  loudong1:'',
  yuanxi1: '',
  // 宿管特有字段
  xingbie2: '',
  loudong2: '',
})

// 注册表单标题
const title = computed(() => {
  switch (loginTable) {
    case 'xuesheng':
      return '学生注册'
    case 'suguan':
      return '宿管注册'
    default:
      return '用户注册'
  }
})

// 表单验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      if (!formRef.value) return
      formRef.value.validateField('confirmPassword', () => null)
    }
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    const reg = /^1[3-9]\d{9}$/
    if (!reg.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }
}

// 基本验证规则
const baseRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ]
}

// 学生特有验证规则
const studentRules = {   
  xingbie1: [
    { required: true, message: '请输入性别', trigger: 'blur' }
  ],
  sushe1: [
    { required: true, message: '请输入宿舍', trigger: 'blur' }
  ],
  yuanxi1: [
    { required: true, message: '请输入院系', trigger: 'blur' }
  ],
  nianling1: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  loudong1: [
    { required: true, message: '请输入楼栋号', trigger: 'blur' }
  ]
}

// 宿管特有验证规则
const dormManagerRules = {
  xingbie2: [
    { required: true, message: '请输入宿管性别', trigger: 'blur' }
  ],
  loudong2: [
    { required: true, message: '请输入宿管管理的楼栋号', trigger: 'blur' }
  ],
}

// 根据不同角色合并验证规则
const rules = computed(() => {
  let result = { ...baseRules }
  
  if (loginTable === 'xuesheng') {
    result = { ...result, ...studentRules }
  } else if (loginTable === 'suguan') {
    result = { ...result, ...dormManagerRules }
  }
  
  return result
})

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 移除确认密码字段
        const submitData = { ...registerForm }
        delete submitData.confirmPassword
        
        // 根据登录表转换字段名
        if (loginTable === 'xuesheng') {
          // 将通用字段名转换为学生特定字段名
          submitData.xueshengzhanghao = submitData.username
          submitData.mima = submitData.password
          submitData.xueshengxingming = submitData.name
          submitData.dianhuahaoma = submitData.phone

          submitData.xingbie = submitData.xingbie1        // 新增性别字段
          submitData.nianling = submitData.nianling1      // 新增年龄字段
          submitData.sushe = submitData.sushe1         // 新增宿舍楼栋映射
          submitData.yuanxi = submitData.yuanxi1          // 原有院系字段
          submitData.loudong = submitData.loudong1
          // 删除通用字段
          delete submitData.username
          delete submitData.password
          delete submitData.name
          delete submitData.phone
          delete submitData.xingbie1        // 新增性别字段
          delete submitData.nianling1      // 新增年龄字段
          delete submitData.sushe1         // 新增宿舍楼栋映射
          delete submitData.yuanxi1          // 原有院系字段
          delete submitData.loudong1
        } else if (loginTable === 'suguan') {
          // 将通用字段名转换为宿管特定字段名
          submitData.suguanzhanghao = submitData.username
          submitData.mima = submitData.password
          submitData.suguanxingming = submitData.name
          submitData.dianhuahaoma = submitData.phone
          submitData.xingbie=submitData.xingbie2
          submitData.loudong = submitData.loudong2
          // 删除通用字段
          delete submitData.username
          delete submitData.password
          delete submitData.name
          delete submitData.phone
          delete submitData.xingbie2
          delete submitData.loudong2
        }
        
        // 添加日志以便调试
        console.log('提交的数据:', submitData)
        
        const data = await userAPI.register(loginTable, submitData)
        
        if (data && data.code === 0) {
          ElMessage.success('注册成功')
          router.push('/login')
        } else {
          ElMessage.error(data.msg || '注册失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('注册失败')
      }
    } else {
      ElMessage.error('请正确填写表单内容')
    }
  })
}

// 返回登录页
const goBack = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  position: relative;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}
</style> 